import 'package:flutter/material.dart';
import 'package:huajianshe_app/base/AppNavigator.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/base/NetworkManager.dart';
import 'package:huajianshe_app/common/AppRouter.dart';
import 'package:huajianshe_app/common/C.dart';
import 'package:huajianshe_app/common/TS.dart';
import 'package:huajianshe_app/common/load_image.dart';
import 'package:huajianshe_app/common/space.dart';
import 'package:huajianshe_app/network/Api.dart';
import 'package:huajianshe_app/network/response/BaseResp.dart';
import 'package:huajianshe_app/pages/circle/CircleDetailPage.dart';
import 'package:huajianshe_app/pages/circle/model/CircleModel.dart';
import 'package:huajianshe_app/pages/main/model/MomentModel.dart';
import 'package:huajianshe_app/pages/user_info/UserInfoItem.dart';
import 'package:huajianshe_app/utils/dialog_util.dart';
import 'package:huajianshe_app/widget/AutoGridWidgetV2.dart';
import 'package:huajianshe_app/widget/RoundedCornerWidget.dart';
import 'package:huajianshe_app/widget/dialog/ShareDialog.dart';
import 'package:oktoast/oktoast.dart';

class MomentItem extends StatefulWidget {

  final void Function(MomentListData)? onComment;
  final void Function()? onShare;
  final void Function()? onLike;
  final MomentListData data;
  final CircleInfo? circleInfo;

  const MomentItem(this.data, this.circleInfo, {Key? key,
    this.onComment,
    this.onShare,
    this.onLike
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _MomentItemState();
  }
}

class _MomentItemState extends BaseState<MomentItem> {

  int? maxLines = 5;
  @override
  Widget build(BuildContext context) {
    print('_MomentItemState: ${widget.circleInfo}');
    return RoundedCornerWidget(radius: 13, padding: EdgeInsets.symmetric(horizontal: 13, vertical: 16),
        width: double.infinity, borderColor: Colors.transparent, backgroundColor: Colors.white,
        boxShadowList: [
          BoxShadow(color: Color.fromRGBO(0x99, 0x49, 0x5D, 0.02), offset: Offset(0, 0), blurRadius: 15, spreadRadius: 0)
        ],
        child:
          Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
            UserInfoItem(widget.data.userInfo, widget.circleInfo),
            H(10),
            GestureDetector(onTap: () { setState(() { maxLines = null; }); }, child:
              Text('${widget.data.content}',
                style: TS(14, C.gray333), maxLines: maxLines, overflow: TextOverflow.fade,),
              ),
            H(10),
            buildMedia(widget.data),
            H(10),
            buildCircles(),
            H(10),
            // Padding(padding: EdgeInsets.symmetric(vertical: 16), child:
              Row(mainAxisSize: MainAxisSize.max, textDirection: TextDirection.rtl,  children: [
                SizedBox(width: 40, child: Text('${widget.data.collectNum}', style: TS(14, C.gray333), overflow: TextOverflow.clip, maxLines: 1, textAlign: TextAlign.start,)),
                W(4),
                GestureDetector(onTap: () { like(widget.data); }, child: LoadImage(widget.data.isCollect == 1 ? 'ic_liked' : 'ic_like')),
                W(4),
                SizedBox(width: 32, child: Text('${widget.data.commentNum}', style: TS(14, C.gray333), overflow: TextOverflow.clip,)),
                W(4),
                GestureDetector(onTap: () { if (widget.onComment != null) widget.onComment!(widget.data); } , child: LoadImage('ic_comment')),
                W(20),
                GestureDetector(onTap: () { DialogUtil.showBottomDialogV2(context, ShareDialog(shareTypes: 22,), radius: 13, bgColor: Colors.transparent,
                    margin: EdgeInsets.symmetric(horizontal: 5)); },
                    child: LoadImage('ic_share')),
                Spacer(),
                Text('${widget.data.postDataTime}', style: TS(13, C.gray666),),


              ])
            // )
          ])
    );
  }

  Widget buildCircles() {
    if ((widget.data.circles?.length ?? 0) > 0) {
      if (widget.data.circles?[0].isJoin == 1) {
        return Wrap(spacing: 5, runSpacing: 5, children: [
          ...buildJoinedCircles(widget.data.circles!)
        ]);
      } else {
        return GestureDetector(onTap: () { joinCircle(widget.data.circles?[0].circleId); },
          child: RoundedCornerWidget(child: Row(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: [
            LoadImage('ic_contacts'),
            W(3),
            Text('${widget.data.circles?[0].title}', style: TS(12, C.gray0D0E15, height: 0.9)),
            W(5),
            VD(18.0, color: C.gray999),
            W(5),
            LoadImage('ic_add'),
            W(3),
            Text('加入', style: TS(12, C.primary, height: 0.9)),
          ]), padding: EdgeInsets.all(7), backgroundColor: C.grayF6, height: 28, radius: 14,),);
      }
    }
    return H(0);
  }

  List<Widget> buildJoinedCircles(List<CircleInfo> circles) {
    List<Widget> result = [];
    for (int i = 0; i < circles.length; i++) {
      if (i > 0) {
        result.add(Text('|', style: TS(12, C.gray333)));
      }
      CircleInfo circle = circles[i];
      if (circle.isCaptain == 1) {
        result.add(
            GestureDetector(onTap: () => joinCircle(circle.circleId),
                child: Row(mainAxisSize: MainAxisSize.min, children: [
                  LoadImage('ic_contacts'),
                  W(3),
                  Text('${circle.title}', style: TS(12, C.gray0D0E15)),
                ])
            )
        );
      } else {
        result.add(
            GestureDetector(onTap: () => joinCircle(circle.circleId),
                child: Text('#${circle.title}', style: TS(12, C.gray0D0E15)))
        );
      }
    }
    return result;
  }

  Widget buildMedia(MomentListData data) {
    if (data.videoInfo != null && data.videoInfo!.length > 0) {
      VideoInfo videoInfo = data.videoInfo![0];
      return GestureDetector(onTap: () { playMedia(videoInfo.videoUrl); },
          child: AspectRatio(aspectRatio: 2,
              child: Stack(children: [
                RoundedCornerWidget(borderColor: Colors.transparent, borderWidth: 0, radius: 3, width: double.infinity,
                    child: LoadImage(videoInfo.coverUrl)),
                Center(child: LoadImage('play_40'),)
              ])
          )
      );
    } else {
      if (data.imgUrls != null && data.imgUrls!.length > 0) {
        return AutoGridImageV2(colNum: 3, padding: 5, imageUrls: data.imgUrls!, radius: 4,);
      } else {
        return H(0);
      }
    }
  }

  void joinCircle(int? id) {
    AppNavigator.push(context, RouteName.CIRCLE_DETAIL, arguments: {'circleDetailType': CircleDetailType.inner, 'circleId': id}); //如果是未加入,inner会自动转变成outer
  }

  void playMedia(String? url) {
    AppNavigator.push(context, RouteName.VIDEO_PLAYER, arguments: {'url': url});
  }

  void like(MomentListData momentListData) { //收藏
    print('like');
    var data = {
      'aim_type': '4',
      'aim_sn': momentListData.postSn,
      'like_type': '2'
    };
    print('data: ${data}');
    NetworkParams api = Api.doLike();
    sendRequest2(BaseResp(), path: api.path, method: api.method, isForm: api.isForm,
        data: data, callback: LikeCallback(this, widget.data));
  }

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {
    super.onReqSuccess(t, code, msg, path);
    if (path.contains(Api.doLike().path) && code == 0) {
      setState(() {});
    }
  }
}

class LikeCallback extends NetworkCallback {

  final NetworkCallback originalCallback;
  final MomentListData data;

  LikeCallback(this.originalCallback, this.data);

  @override
  void onReqError(int code, String msg) { originalCallback.onReqError(code, msg); }

  @override
  void onReqFinish() { originalCallback.onReqFinish(); }

  @override
  void onReqStart() {}

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {
    if (path.contains(Api.doLike().path) && code == 0) {
      print('ok like');
      if (data.isCollect == 1) {
        data.isCollect = 0;
        data.collectNum = (data.collectNum ?? 1) - 1;
      } else {
        data.isCollect = 1;
        data.collectNum = (data.collectNum ?? 0) + 1;
      }
      originalCallback.onReqSuccess(t, code, msg, path);
    }
    showToast(msg);
  }
}

class MomentType {//  1.好友 2.推荐 3.圈内公开动态 4.圈内所有动态 5.指定圈主所有动态 6.指定好友所有动态）
  static const int MOMENT_TYPE_FRIEND = 1;
  static const int MOMENT_TYPE_RECOMMENDATION = 2;
  static const int MOMENT_TYPE_PUBLIC_IN_CIRCLE = 3;
  static const int MOMENT_TYPE_ALL_IN_CIRCLE = 4;
  static const int MOMENT_TYPE_ALL_FROM_CAPTION = 5;
  static const int MOMENT_TYPE_ALL_FROM_FRIEND = 6;

}

class MomentBusinessType { // 业务类型 1动态2商机，默认全部
  static const int MOMENT = 1;
  static const int OPPORTUNITY = 2;
}